<template>
  <div class="artist-list">
    <el-card>
      <!-- 页面标题和操作按钮 -->
      <div class="page-header">
        <div class="header-left">
          <h2>艺人管理</h2>
          <p class="description">管理音乐节艺人信息，包括基本信息、头像、演出安排等</p>
        </div>
        <div class="header-right">
          <el-button 
            v-if="userStore.hasPermission(ALL_PERMISSIONS.ARTIST_CREATE)"
            type="primary" 
            @click="showCreateDialog"
          >
            <el-icon><Plus /></el-icon>
            添加艺人
          </el-button>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.search"
              placeholder="搜索艺人姓名、描述等"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
              <el-option label="启用" value="ACTIVE" />
              <el-option label="禁用" value="INACTIVE" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 艺人列表 -->
      <el-table
        v-loading="loading"
        :data="artistList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="头像" width="100">
          <template #default="{ row }">
            <el-avatar 
              :src="row.avatar" 
              :size="50"
              :icon="UserFilled"
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="艺人姓名" min-width="120" />
        <el-table-column prop="country" label="国家/地区" width="100" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'ACTIVE' ? 'success' : 'danger'">
              {{ row.status === 'ACTIVE' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="演出数量" width="100">
          <template #default="{ row }">
            <el-tag type="info">{{ row.stats?.performanceCount || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="userStore.hasPermission(ALL_PERMISSIONS.ARTIST_READ)"
              size="small" 
              @click="viewArtist(row)"
            >
              查看
            </el-button>
            <el-button 
              v-if="userStore.hasPermission(ALL_PERMISSIONS.ARTIST_UPDATE)"
              size="small" 
              type="primary" 
              @click="editArtist(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="userStore.hasPermission(ALL_PERMISSIONS.ARTIST_DELETE)"
              size="small" 
              type="danger" 
              @click="deleteArtist(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
                  :current-page="pagination.page"
        :page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑艺人对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '创建艺人' : '编辑艺人'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="艺人姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入艺人姓名" />
        </el-form-item>
        <el-form-item label="国家/地区" prop="country">
          <el-input v-model="form.country" placeholder="请输入国家/地区" />
        </el-form-item>
        <el-form-item label="艺人描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入艺人描述"
          />
        </el-form-item>
        <el-form-item label="头像" prop="avatar" v-if="dialogType === 'edit' && form.id">
          <el-input v-model="form.avatar" placeholder="请输入头像URL" />
          <div  class="upload-section">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :action="`/api/admin/artists/${form.id}/avatar`"
              accept="image/*"
              :headers="{ Authorization: `Bearer ${userStore.token}` }"
              name="avatar"
            >
              <el-button size="small" type="primary">上传头像</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="横幅图片" prop="bannerImage" v-if="dialogType === 'edit' && form.id">
          <el-input v-model="form.bannerImage" placeholder="请输入横幅图片URL" />
          <div class="upload-section">
            <el-upload
              class="banner-uploader"
              :show-file-list="false"
              :before-upload="beforeBannerUpload"
              :on-success="handleBannerSuccess"
              :on-error="handleBannerError"
              :action="`/api/admin/artists/${form.id}/banner`"
              accept="image/*"
              :headers="{ Authorization: `Bearer ${userStore.token}` }"
              name="bannerImage"
            >
              <el-button size="small" type="primary">上传横幅</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
                  <el-radio-group v-model="form.status">
          <el-radio value="ACTIVE">启用</el-radio>
          <el-radio value="INACTIVE">禁用</el-radio>
        </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            {{ dialogType === 'create' ? '创建' : '更新' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 艺人详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="艺人详情"
      width="800px"
    >
      <div v-if="currentArtist" class="artist-detail">
        <div class="artist-header">
          <el-avatar :src="currentArtist.avatar" :size="80" :icon="UserFilled" />
          <div class="artist-info">
            <h3>{{ currentArtist.name }}</h3>
            <p class="artist-meta">
              <el-tag :type="currentArtist.status === 'ACTIVE' ? 'success' : 'danger'">
                {{ currentArtist.status === 'ACTIVE' ? '启用' : '禁用' }}
              </el-tag>
              <span v-if="currentArtist.country">{{ currentArtist.country }}</span>
            </p>
          </div>
        </div>
        
        <el-divider />
        
        <div class="artist-content">
          <div v-if="currentArtist.description" class="description">
            <h4>艺人描述</h4>
            <p>{{ currentArtist.description }}</p>
          </div>
          
          <div v-if="currentArtist.bannerImage" class="banner">
            <h4>横幅图片</h4>
            <img :src="currentArtist.bannerImage" alt="横幅图片" class="banner-image" />
          </div>
          
          <div class="stats">
            <h4>统计信息</h4>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-number">{{ currentArtist._count?.performances || 0 }}</div>
                  <div class="stat-label">演出场次</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-number">{{ currentArtist?._count?.votes || 0 }}</div>
                  <div class="stat-label">投票数</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-number">{{ currentArtist?._count?.works || 0 }}</div>
                  <div class="stat-label">作品数</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, UserFilled, Picture } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { artistApi } from '@/api'
import { ALL_PERMISSIONS } from '@/constants/permissions'
import type { Artist, CreateArtistRequest, UpdateArtistRequest } from '@/types'
import { formatDate } from '@/utils/format'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const artistList = ref<Artist[]>([])
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

const searchForm = reactive({
  search: '',
  status: ''
})

// 对话框相关
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogType = ref<'create' | 'edit'>('create')

const currentArtist = ref<Artist | null>(null)
const formRef = ref()

const form = reactive<CreateArtistRequest & { id?: number }>({
  name: '',
  description: '',
  avatar: '',
  bannerImage: '',
  country: '',
  status: 'ACTIVE'
})

const rules = {
  name: [
    { required: true, message: '请输入艺人姓名', trigger: 'blur' },
    { min: 1, max: 50, message: '艺人姓名长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  country: [
    { required: true, message: '请输入国家/地区', trigger: 'blur' }
  ]
}

// 获取艺人列表
const fetchArtists = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      ...searchForm
    }
    const response = await artistApi.getList(params)
    artistList.value = response.data.data
    pagination.total = response.data.pagination.total
    pagination.page = response.data.pagination.page
    pagination.limit = response.data.pagination.limit
  } catch (error) {
    ElMessage.error('获取艺人列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchArtists()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    search: '',
    status: ''
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  fetchArtists()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchArtists()
}

// 显示创建对话框
const showCreateDialog = () => {
  dialogType.value = 'create'
  dialogVisible.value = true
  resetForm()
}

// 编辑艺人
const editArtist = (artist: Artist) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.assign(form, {
    id: artist.id,
    name: artist.name,
    description: artist.description,
    avatar: artist.avatar,
    bannerImage: artist.bannerImage,
    country: artist.country,
    status: artist.status
  })
}

// 查看艺人详情
const viewArtist = async (artist: Artist) => {
  try {
    const response = await artistApi.get(artist.id)
    currentArtist.value = response.data
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取艺人详情失败')
  }
}

// 删除艺人
const deleteArtist = async (artist: Artist) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除艺人 "${artist.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await artistApi.delete(artist.id)
    ElMessage.success('删除成功')
    fetchArtists()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: undefined,
    name: '',
    description: '',
    avatar: '',
    bannerImage: '',
    country: '',
    status: 'ACTIVE'
  })
  formRef.value?.clearValidate()
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (dialogType.value === 'create') {
      const { id, ...createData } = form
      await artistApi.create(createData)
      ElMessage.success('创建成功')
    } else {
      const { id, ...updateData } = form
      await artistApi.update(id!, updateData)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    fetchArtists()
  } catch (error) {
    ElMessage.error(dialogType.value === 'create' ? '创建失败' : '更新失败')
  } finally {
    submitLoading.value = false
  }
}

// 头像上传
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传头像只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarSuccess = (response: any) => {
  form.avatar = response.data.avatar
  ElMessage.success('头像上传成功')
}

const handleAvatarError = () => {
  ElMessage.error('头像上传失败')
}

// 横幅上传
const beforeBannerUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('上传横幅只能是图片格式!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('上传横幅大小不能超过 5MB!')
    return false
  }
  return true
}

const handleBannerSuccess = (response: any) => {
  form.bannerImage = response.data.bannerImage
  ElMessage.success('横幅上传成功')
}

const handleBannerError = () => {
  ElMessage.error('横幅上传失败')
}

// 初始化
onMounted(() => {
  fetchArtists()
})
</script>

<style scoped>
.artist-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
}

.banner-uploader {
  text-align: center;
}

.banner-uploader .banner {
  width: 200px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

.banner-uploader .banner-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
}

.artist-detail {
  padding: 20px 0;
}

.artist-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.artist-info h3 {
  margin: 0 0 10px 0;
  color: #303133;
}

.artist-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #909399;
  font-size: 14px;
}

.artist-content {
  color: #606266;
}

.artist-content h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.description {
  margin-bottom: 20px;
}

.banner {
  margin-bottom: 20px;
}

.banner-image {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
}

.stats {
  margin-top: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.upload-section {
  margin-top: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.upload-section .el-upload {
  display: block;
}
</style>